package com.sanjin.service.impl;

import com.sanjin.entity.ParkSpace;
import com.sanjin.entity.ParkSpaceWxMiniUserRelation;
import com.sanjin.exception.MyException;
import com.sanjin.repository.ParkSpaceWxMiniUserRelationRepository;
import com.sanjin.service.ParkSpaceService;
import com.sanjin.service.ParkSpaceWxMiniUserRelationService;
import com.sanjin.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @description:
 * @author: sanjin
 * @date: 2019/7/3 10:40
 */
@Service
public class ParkSpaceWxMiniUserRelationServiceImpl implements ParkSpaceWxMiniUserRelationService {

    @Autowired
    private ParkSpaceService parkSpaceService;

    @Autowired
    private ParkSpaceWxMiniUserRelationRepository parkSpaceWxMiniUserRelationRepository;

    @Autowired
    private SecurityUtils securityUtils;


    @Transactional
    @Override
    public void userSelectParkSpace(Integer parkSpaceId) {
        // 验证parkSpaceId是否存在
        if (parkSpaceId == null) throw new MyException("parkSpaceId不能为空");
        ParkSpace parkSpace = parkSpaceService.queryParkSpaceByParkSpaceId(parkSpaceId);
        if (parkSpace == null) throw new MyException("parkSpaceId不存在");

        // 查询该车位是否已经被占用
        if (!this.queryParkSpaceIdIsFree(parkSpaceId)) {
            throw new MyException("该车为正在被使用");
        }

        // 创建车辆选择停车位
        ParkSpaceWxMiniUserRelation pwur =
                new ParkSpaceWxMiniUserRelation()
                .setParkSpaceId(parkSpaceId)
                .setWxMiniUserId(securityUtils.getWxMiniUser().getId())
                ;
        parkSpaceWxMiniUserRelationRepository.save(pwur);

        // 将车位状态设置为false
        parkSpace.setStatus(1);
        parkSpaceService.save(parkSpace);
    }

    @Override
    public Boolean queryParkSpaceIdIsFree(Integer parkSpaceId) {
        ParkSpaceWxMiniUserRelation parkSpaceWxMiniUserRelation = parkSpaceWxMiniUserRelationRepository.queryByParkSpaceIdAndIsLeave(parkSpaceId, 0);
        if (parkSpaceWxMiniUserRelation == null) {
            return true;
        }
        return false;
    }
}
